package tpase.client.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import it.unisa.dia.gas.jpbc.Element;
import tpase.client.VO.Message;
import tpase.client.VO.StatusCode;

import java.util.List;
import java.util.Map;

public class ClientAuthHandler extends ChannelInboundHandlerAdapter {
    private final Element auth_uid_i;
    private String uid;
    private final Object registerLock;
    private List<Boolean> regSuccessList;

    public ClientAuthHandler(String uid, Element auth_uid_i, Object registerLock, List<Boolean> regSuccessList) {
        this.auth_uid_i = auth_uid_i;
        this.uid = uid;
        this.registerLock = registerLock;
        this.regSuccessList = regSuccessList;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Message request = new Message(StatusCode.AUTH_STORE_REQUEST);
        Map<String, byte[]> map = request.getMap();
        map.put("auth_uid_i", auth_uid_i.toBytes());
        map.put("uid", uid.getBytes());
        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message respond = (Message) msg;
        int statusCode = respond.getStatusCode();
        synchronized (registerLock) {
            if (statusCode == StatusCode.AUTH_STORE_SUCCESS_RESPONSE) {
                regSuccessList.add(true);
            } else if (statusCode == StatusCode.AUTH_STORE_FAIL_RESPONSE) {
                regSuccessList.add(false);
                System.out.println("Auth_Info_Response fail");
            }
            registerLock.notifyAll();
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught: 发生异常，关闭通道");
        System.out.println(cause.toString());
        ctx.close();
    }
}
